package mobilesearch.thread;

import android.content.ContentResolver;
import mobilesearch.data.ImageData;
import mobilesearch.data.VideoData;
import mobilesearch.ui.BroadcastCommand;

import java.util.ArrayList;
import android.database.Cursor;
import android.provider.MediaStore;
import android.util.Log;
import android.content.Intent;
import android.content.Context;

public class VideoSearchThread extends Thread {
	
	private static final String TAG = "VideoSearchThread";
	private ContentResolver resolver;
	private Context context;

	private String videoId;
	private String videoName;
	private String videoTime;
	
	public VideoSearchThread(Context context, ContentResolver resolver) {
		super();
		this.context = context;
		this.resolver = resolver;
	}

	@Override
	public void run() {
		super.run();
		ArrayList<VideoData> videoList = new ArrayList<VideoData>();
		
		Cursor cursor = null;
		try{
			cursor = this.resolver.query(MediaStore.Video.Media.INTERNAL_CONTENT_URI, null, null, null, null);
			if(cursor.moveToFirst()){
				Log.i(TAG, "INTERNAL_CONTENT_URI");
				this.Search(cursor, videoList);
			}
			
			cursor = this.resolver.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
			if(cursor.moveToFirst()){
				Log.i(TAG, "EXTERNAL_CONTENT_URI");

				this.Search(cursor, videoList);
			}
		}catch(Exception exception){
			Log.i(TAG, exception.toString());
		}
		
		//broadcast the video data
		if(!videoList.isEmpty()){
			Intent videoIntent = new Intent(BroadcastCommand.SEARCH_VIDEO);
			videoIntent.putParcelableArrayListExtra(BroadcastCommand.SEARCH_VIDEO, videoList);
			this.context.sendBroadcast(videoIntent);
		}
	}
	
	
	private void Search(Cursor cursor, ArrayList<VideoData> videoList){
		do{
			VideoData data = new VideoData();
			
			int idIndex = cursor.getColumnIndex(MediaStore.Video.Media._ID);
			this.videoId = cursor.getString(idIndex);
			data.setVideoId(this.videoId);
			
			int videoNameIndex = cursor.getColumnIndex(MediaStore.Video.Media.TITLE);
			this.videoName = cursor.getString(videoNameIndex);
			data.setVideoName(videoName);
			
			int timeIndex = cursor.getColumnIndex(MediaStore.Video.Media.DATE_TAKEN);
			this.videoTime = cursor.getString(timeIndex);
			data.setVideoTime(videoTime);
			
			videoList.add(data);
			
		}while(cursor.moveToNext());
	}

}
